package ictbk.ttmk51.grapro.app.safephonebook;

import ictbk.ttmk51.grapro.app.R;
import ictbk.ttmk51.grapro.app.common.Constant;
import ictbk.ttmk51.grapro.app.common.MyActivity;
import ictbk.ttmk51.grapro.app.utils.ContactProvider;
import ictbk.ttmk51.grapro.app.utils.IconContextMenu;
import ictbk.ttmk51.grapro.app.utils.IconContextMenu.IconContextMenuOnClickListener;

import java.util.ArrayList;
import java.util.HashMap;

import ictbk.ttmk51.grapro.app.utils.DateFormat;
import ictbk.ttmk51.grapro.app.LoginActivity;
import ictbk.ttmk51.grapro.app.service.*;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

public class SafePhoneBookActivity extends MyActivity implements Constant, OnItemClickListener {
	
	private final int CONTEXT_MENU_ID = 1;
	private IconContextMenu iconContextMenu = null;
	private final int SELECT_CONTEXT_MENU_ITEM = 1;
	private final int EDIT_CONTEXT_MENU_ITEM = 3;
	private final int DELETE_CONTEXT_MENU_ITEM = 4;
	
	private int							numberOfItemSelected	= 0;
	private int							item_position_long_clicked;
	private ArrayList<Contact>	items;
	private ListView					lvContact;
	private ArrayAdapter<Contact>	aa;
	ContactProvider						cp;
	Handler								myHandler				= new Handler();
	
	/**
	 * Ham nay dat lai gia tri cho bien: numberOfItemSelected Bien nay nham muc
	 * dich dem so item da select de set label cho menu item Select All truong
	 * hop numberOfItemSelected = so luong hien co thi set label la "Select All"
	 * nguoc lai thi set la "Unselect All"
	 */
	private void countItemChecked() {
		numberOfItemSelected = 0;
		for (int i = 0; i < items.size(); i++) {
			if (items.get(i).isChecked()) {
				numberOfItemSelected++;
			}
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTitle("Phone Book");
//		requestWindowFeature(Window.FEATURE_LEFT_ICON);
		setContentView(R.layout.contact_list);
//		setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.phonebook_backup);
		
		lvContact = (ListView) findViewById(R.id.List);
		try {
			cp = new ContactProvider();
			cp.setCr(getContentResolver());
			cp.setCur(getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, "display_name ASC"));

			items = cp.readBaseContactInfo();
			// sections = cp.readBaseContactInfo0();
			if (items.isEmpty()) {
				((TextView) findViewById(R.id.tvMessageEmptyList)).setText(R.string.msg_EmptyListContact);
			} else {
				((TextView) findViewById(R.id.tvMessageEmptyList)).setText("");
			}
			
			countItemChecked();

			aa = new ArrayAdapter<Contact>(this, R.layout.list_contact_info, items) {
				@Override
				public View getView(int position, View v, ViewGroup parent) {
					if (v == null) {
						LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
						v = vi.inflate(R.layout.list_contact_info, null);
					}
					Contact contact = items.get(position);
					if (contact != null) {
						TextView tvFirstName = (TextView) v.findViewById(R.id.tvFirstName);
						TextView tvLastName = (TextView) v.findViewById(R.id.tvLastName);

						ImageView imgAvatar = (ImageView) v.findViewById(R.id.ImageAvatar);
						imgAvatar.setImageBitmap(contact.getBitmap());
						
						final CheckBox chkSelectContact = (CheckBox) v.findViewById(R.id.chkSelectContact);
						chkSelectContact.setChecked(contact.isChecked());

						HashMap<String, String> info = cp.getContactInfoToShow(contact);
						tvFirstName.setText(contact.getDisplayName());
						tvFirstName.setText(contact.getFirstName(info.get("DisplayName")));
						tvLastName.setText(contact.getLastName(info.get("DisplayName")));
					}
					return v;
				}
			};
//			lvContact.setOnCreateContextMenuListener(this);
			lvContact.setOnItemClickListener(this);
			lvContact.setOnItemLongClickListener(itemLongClickListener);
			lvContact.setAdapter(aa);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		//Add item for context menu
		addItemContextMenu();
		onClickItemContextMenu();
		
//		new AlertNewContact().start();
	}
	
	//Set onclicklistener when click item of contact list
	@SuppressWarnings("deprecation")
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
//		Toast.makeText(SafePhoneBookActivity.this, "Clicked!", Toast.LENGTH_LONG).show();
		try{
			Intent intent = new Intent();
			intent.setAction(Intent.ACTION_VIEW);
			intent.setData(Uri.withAppendedPath(android.provider.Contacts.People.CONTENT_URI, "" + items.get(arg2).getId()));
			startActivity(intent);
		}catch(Exception e){
			new AlertDialog.Builder(SafePhoneBookActivity.this).setMessage(e.getMessage()).show();
		}
	}
	
	private OnItemLongClickListener itemLongClickListener = new OnItemLongClickListener() {

		@Override
		public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
				int arg2, long arg3) {
			// TODO Auto-generated method stub
			item_position_long_clicked = arg2;
			showDialog(arg2);
			return true;
		}
	};
	
	/**
	 * Create context menu
	 */
	protected Dialog onCreateDialog(int id){
		Log.i("ID Dialog", String.valueOf(id));
		return iconContextMenu.createMenu(items.get(id).getDisplayName());
	}
	
	public void setOnClickCheckBox(View v){
		CheckBox chk = (CheckBox) v;
		int pos = lvContact.getPositionForView(v);
		Contact myContact = aa.getItem(pos);
		myContact.setChecked(chk.isChecked());
		numberOfItemSelected = chk.isChecked() ? 1 : -1;
	}
	
	public void addItemContextMenu(){
		Resources res = getResources();
		iconContextMenu = new IconContextMenu(this, CONTEXT_MENU_ID);
		iconContextMenu.addItem(res, "Select", R.drawable.select, SELECT_CONTEXT_MENU_ITEM);
		iconContextMenu.addItem(res, "Edit", R.drawable.edit, EDIT_CONTEXT_MENU_ITEM);
		iconContextMenu.addItem(res, "Delete", R.drawable.remove_user, DELETE_CONTEXT_MENU_ITEM);
	}
	
	public void onClickItemContextMenu(){
		iconContextMenu.setOnClickListener(new IconContextMenuOnClickListener() {
			
			@Override
			public void onClick(int menuId) {
				// TODO Auto-generated method stub
				switch(menuId){
				case SELECT_CONTEXT_MENU_ITEM:
				{
					//do something - select
					items.get(item_position_long_clicked).setChecked(!items.get(item_position_long_clicked).isChecked());
					numberOfItemSelected += items.get(item_position_long_clicked).isChecked()? 1 : -1;
					aa.notifyDataSetChanged();
					break;
				}
				case EDIT_CONTEXT_MENU_ITEM:
				{
					Intent intent = new Intent();
					intent.setAction(Intent.ACTION_EDIT);
					intent.setData(Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, "" + items.get(item_position_long_clicked).getId()));
					startActivity(intent);
					break;
				}
				case DELETE_CONTEXT_MENU_ITEM:
				{
					//do something - delete
					showConfirmDiaglog("Confirm Delete", "Are you sure? \n Delete: "+ items.get(item_position_long_clicked).getDisplayName(), new OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							if(cp.deleteContactWithID(items.get(item_position_long_clicked).getId()) == 0)
								if(cp.deleteContactWithName(items.get(item_position_long_clicked).getDisplayName()) == 0){
									showToast("Error\nCan not delete");
								}else{
									items.remove(item_position_long_clicked);
									numberOfItemSelected --;
									aa.notifyDataSetChanged();
								}
							else{
								items.remove(item_position_long_clicked);
								numberOfItemSelected --;
								aa.notifyDataSetChanged();
							}
						}
					});
					
					break;
				}
					
				}
			}
		});
	}
	
	@Override
	protected void onRestart(){
		onCreate(getIntent().getExtras());
		super.onRestart();
	}
	
	//Option Menu
	@Override
	public boolean onCreateOptionsMenu(Menu menu){
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.safephonebook_options_menu, menu);
		return true;
	}
	
	@Override
	public boolean onMenuOpened(int featureId, Menu menu) {
		if (numberOfItemSelected == items.size()) {
			menu.findItem(R.id.select_all).setTitle(R.string.option_menu_item_UnselectAll);
		} else {
			menu.findItem(R.id.select_all).setTitle(R.string.option_menu_item_SelectAll);
		}
		return super.onMenuOpened(featureId, menu);
	}
	
	public boolean onOptionsItemSelected(MenuItem item){
		switch(item.getItemId()){
		case R.id.new_contact:
			Intent intent = new Intent(Intent.ACTION_INSERT);
			intent.setData(ContactsContract.Contacts.CONTENT_URI);
			startActivity(intent);
			break;
		case R.id.select_all:
			if(numberOfItemSelected == items.size()){
				//Unselect All
				for(Contact contact : items)
					contact.setChecked(false);
				numberOfItemSelected = 0;
			}else{
				// Sellect all
				for(Contact contact : items)
					contact.setChecked(true);
				numberOfItemSelected = items.size();
			}
			showToast("You selected all contact!");
			aa.notifyDataSetChanged();
			break;
		case R.id.delete:
			showConfirmDiaglog("Confirm Delete", "Are you sure delete?", new OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					final ProgressDialog pd = showProgressDialog("Deleting...", false);
					new Thread(){
						public void run(){
							int count = 0;
							for(int i = 0; i < items.size(); i++){
								Contact contact = items.get(i);
								if(contact.isChecked()){
									if(count < (count += cp.deleteContactWithID(contact.getId()))){
										items.remove(i);
										numberOfItemSelected--;
										i--;
									}else{
										if(count < (count + cp.deleteContactWithName(contact.getDisplayName()))){
											items.remove(i);
											numberOfItemSelected--;
											i--;
										}
									}
									
									myHandler.post(new Thread(){
										public void run(){
											pd.setMessage("finish");
										}
									});
								}
							}
							myHandler.post(new Thread(){
								public void run(){
									if(items.isEmpty())
										((TextView)findViewById(R.id.tvMessageEmptyList)).setText(R.string.msg_EmptyListContact);
									else
										((TextView)findViewById(R.id.tvMessageEmptyList)).setText("");
									aa.notifyDataSetChanged();
									pd.dismiss();
								}
							});
						}
					}.start();
				}
			});
			break;
		case R.id.uploadPhonebook:
			if (items.isEmpty()) {
				showToast(R.string.msg_EmptyListContact);
			} else {
				
				showBackupDialog();
				
			}
			break;
		case R.id.revertPhonebook:
			Intent i = new Intent(SafePhoneBookActivity.this, RestoreContactActivity.class);
			startActivity(i);
			break;
		}
		return false;
	}
	
	
	//Dialog Backup PhoneBook
	public void showBackupDialog() {
		final LinearLayout ll = new LinearLayout(this);
		final EditText inputBoxNotes = new EditText(this, null);

		ll.setOrientation(LinearLayout.VERTICAL);
		ll.setPadding(5, 5, 5, 5);
		ll.addView(inputBoxNotes, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
		inputBoxNotes.setHint("Notes");
		new AlertDialog.Builder(this).setView(ll).setIcon(R.drawable.backup_icon).setTitle("Backup Contact").setPositiveButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface d, int which) {
				final ProgressDialog pd = showProgressDialog(null, "Please waiting...", false);
				new Thread() {
					public void run() {
						String notes = inputBoxNotes.getText().toString();
						try {
							if (GetWebservice.backupPhoneBook(cp.readFullContactInfo(), LoginActivity.getUserID(), getDate(DateFormat.DDMMYYYY, "-"), getTime(), notes)) {
								myHandler.post(new Runnable() {
									public void run() {
										showToast("Backup completed");
									}
								});
							} else {
								myHandler.post(new Runnable() {
									public void run() {
										showToast("Backup error!");
									}
								});
							}
						} catch (final Exception e) {
							myHandler.post(new Runnable() {
								public void run() {
									showErrorDialog("Please check again connection." + e.getMessage());
								}
							});
						}
						pd.dismiss();
					}
				}.start();
			}
		}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface d, int which) {
				d.dismiss();
			}
		}).create().show();
	}
}
